package com.sam.a_jdbctemplate;

import com.mysql.jdbc.StringUtils;
import com.sam.bean.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 使用JDBC模板实现增删改查
 *
 * @Author: SamZhao
 * @Description:
 * @Date: 2018/01/13 17:00
 */
public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    @Override
    public int save(User user) {
        //书写sql 并执行
        String sql = "insert into t_user values(null, ?);";
        int result = jdbcTemplate.update(sql, user.getName());
        return result;
    }

    @Override
    public int delete(Integer id) {
        //书写sql 并执行
        String sql = "delete t_user t where t.id = ?;";
        int result = jdbcTemplate.update(sql, id);
        return result;
    }

    @Override
    public int update(User user) {
        //书写sql 并执行
        String sql = "update t_user t set t.name = ? where t.id = ? ;";
        int result = jdbcTemplate.update(sql, user.getName(), user.getId());
        return result;
    }

    @Override
    public User getById(Integer id) {
        String sql = "select * from t_user t where t.id = ? ;";
        return jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"))
                return user;
            }
        }, id);
    }

    @Override
    public int getTotalCount() {
        return 0;
    }

    @Override
    public List<User> getAll() {
        return null;
    }
}
